package com.jili.helloword.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.sctp.nio.NioSctpChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

/**
 * @author: Jili
 * @date: Created on 2022/4/20 16:03
 * 客户端启动类
 */
public class AppClientHello {
    private  final String host;
    private  final int port;

    public AppClientHello(String host,int port) {
        this.host = host;
        this.port = port;
    }

    public void run() throws Exception{
        /**
         * 配置相应的参数,提供连接到远端
         */

        EventLoopGroup group = new NioEventLoopGroup();//io线程池

        EventLoopGroup work = new NioEventLoopGroup();

        try {
            Bootstrap bs = new Bootstrap();//启动辅助对象
            bs.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host,port))
                    .handler(new ChannelInitializer<SocketChannel>() { //进行通道初始化配置
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new HandlerClientHello()); //添加自定义handler
                        }
                    });
            //连接到远程节点，等待连接完成
            ChannelFuture future = bs.connect().sync();

            //发送消息到服务器
            future.channel().writeAndFlush(Unpooled.copiedBuffer("发送消息：hello world", CharsetUtil.UTF_8));

            //阻塞操作,closeFuture开启一个channel的监听器（这期间channel进行各种工作），直到链路断开
            future.channel().closeFuture().sync();

        } finally {
            group.shutdownGracefully().sync();
        }

    }

    public static void main(String[] args) throws Exception{
        new AppClientHello("127.0.0.1",18080).run();
    }
}
